extends CharacterBody2D

@export var gravity = 500
@export var maxForce = 750
@export var minForce = 100
@export var chargeTime = 3
@onready var jump: AudioStreamPlayer2D = $Jump

const startPos = Vector2(432, 725)

var isCharging = false
var chargeStartTime = 0
var inAir = false
var dead = false

func reset():
	dead = false
	inAir = false
	position = startPos
	set_rotation(0)
	$Respawn.play()

func getForce() -> float:
	var cDuration = clamp(Time.get_ticks_msec() / 1000.0 - chargeStartTime, 0, chargeTime)
	var jumpForce = minForce + (maxForce - minForce) * (cDuration / chargeTime)
	return jumpForce
	
func _physics_process(delta: float) -> void:
	if not is_on_floor():
		velocity.y += gravity * delta
		$AnimatedSprite2D.play("Flying")
		inAir = true
		
	else:
		velocity.y = 0
		velocity.x = 0
		inAir = false
		
	if !inAir:
		if Input.is_action_just_pressed("move_up"):
			isCharging = true
			inAir = false
			chargeStartTime = Time.get_ticks_msec() / 1000.0
			$AnimatedSprite2D.play("Charge")
		
		elif Input.is_action_just_released("move_up") and isCharging:
			isCharging = false
			inAir = true
			velocity.y = -getForce()
			$Jump.play()

		
	if inAir:
		if Input.is_action_just_pressed("move_left"):
			velocity.x = -15000 * delta
			
		if Input.is_action_just_pressed("move_right"):
			velocity.x = 15000 * delta
				
		if Input.is_action_just_released("move_left"):
			velocity.x = 0
				
		if Input.is_action_just_released("move_right"):
			velocity.x = 0
			
			
	if !inAir and !isCharging:
		$AnimatedSprite2D.play("Idle")
	
	if dead:
		set_rotation(PI)
		$AnimatedSprite2D.stop()
	
		
	move_and_slide()
